package com.wennimei.service;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.InputSource;

import com.wennimei.dao.NewsDAO;
import com.wennimei.domain.SinaNews;
import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.util.HttpUtil;
import com.wennimei.util.ShortUrlUtil;
import com.wennimei.util.Switcher;
import com.wennimei.util.TimeUtil;

public class NewsService {

    private static Logger log = Logger.getLogger(NewsService.class);

    private static String treeUrl = "http://rss.sina.com.cn/sina_all_opml.xml";

    private final static Map<String, String> urlMap = new HashMap<String, String>();

    @Autowired
    private Switcher switcher;

    @Autowired
    private NewsDAO newsDAO;

    @SuppressWarnings("unchecked")
    void init() {

        if (!switcher.isOpen())
            return;
        long start = System.currentTimeMillis();
        log.info("start init news tree");
        try {
            InputStream in = HttpUtil.getStream(treeUrl);
            BufferedReader br = new BufferedReader(new InputStreamReader(in,
                    "utf-8"));
            String xmlString = "";
            for (String temp = br.readLine(); temp != null; xmlString += temp, temp = br
                    .readLine());
            InputStream stream2 = new ByteArrayInputStream(
                    xmlString.getBytes("utf-8"));
            SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("utf-8");
            Document doc = (Document) saxReader.read(new InputSource(stream2));
            Element e = doc.getRootElement();
            for (Iterator<Element> i = e.elementIterator(); i.hasNext();) {
                Element element = (Element) i.next();

                if (element.getName().equals("body")) {
                    for (Iterator<Element> j = element.elementIterator(); j
                            .hasNext();) {
                        Element u = (Element) j.next();
                        if (u.getName().equals("outline")) {
                            for (Iterator<Element> k = u.elementIterator(); k
                                    .hasNext();) {
                                Element x = (Element) k.next();
                                urlMap.put(x.attributeValue("text"),
                                        x.attributeValue("xmlUrl"));
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            log.error("crawl news tree error", e);
        }
        log.info("end init news tree :" + (System.currentTimeMillis() - start));
        log.info("start init news content");
        try {
            for (String s: urlMap.keySet()) {
                try {
                    String url = urlMap.get(s);
                    InputStream in = HttpUtil.getStream(url);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in, "utf-8"));
                    String xmlString = "";
                    for (String temp = br.readLine(); temp != null; xmlString += temp, temp = br
                            .readLine());
                    InputStream stream2 = new ByteArrayInputStream(
                            xmlString.getBytes("utf-8"));
                    SAXReader saxReader = new SAXReader();
                    saxReader.setEncoding("utf-8");
                    Document doc = (Document) saxReader.read(new InputSource(
                            stream2));
                    Element e = doc.getRootElement();
                    for (Iterator<Element> i = e.elementIterator(); i.hasNext();) {
                        try {
                            Element element = (Element) i.next();
                            for (Iterator<Element> j = element
                                    .elementIterator(); j.hasNext();) {
                                try {
                                    Element u = (Element) j.next();
                                    if (u.getName().equals("item")) {
                                        SinaNews news = new SinaNews();
                                        for (Iterator<Element> k = u
                                                .elementIterator(); k.hasNext();) {
                                            try {
                                                Element x = (Element) k.next();
                                                if (x.getName().equals("title"))
                                                    news.setTitle(((String) x
                                                            .getData()).trim());
                                                else if (x.getName().equals(
                                                        "link"))
                                                    news.setLink(ShortUrlUtil
                                                            .getShortUrl((String) x
                                                                    .getData()));
                                                else if (x.getName().equals(
                                                        "pubDate"))
                                                    news.setPubDate((String) x
                                                            .getData());
                                                else if (x.getName().equals(
                                                        "description"))
                                                    news.setDescription(((String) x
                                                            .getData()).trim());
                                            } catch (Exception e1) {

                                            }
                                        }
                                        newsDAO.insert(news, s);
                                    }
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            log.info("end init news content:"
                    + (System.currentTimeMillis() - start));
        } catch (Exception e) {
            log.error("crawl news  error", e);
        }
    }

    public List<SinaNews> get(String content) {
        content = content.replaceAll(MessageTypeEnum.NEWS.getReplaceRegx(), "");
        if (content.isEmpty())
            content = null;
        String type = null;
        for (String key: urlMap.keySet()) {
            if (null != content
                    && (key.contains(content) || content.contains(key))) {
                type = key;
                break;
            }
        }
        List<SinaNews> res = null;
        if (null == type)
            res = this.newsDAO.get(TimeUtil.formatDate(TimeUtil
                    .getPureDate(new Date())));
        else {
            res = this.newsDAO.getByType(type,
                    TimeUtil.formatDate(TimeUtil.getPureDate(new Date())));
            if (null == res || res.isEmpty())
                res = this.newsDAO.getByType(type);
        }
        return res;
    }
}
